<!--vue模板-->
<template>
  <div>
    <div
      class="tip"

    >
      {{ isEditMode ? '  修改询价清单以及要求' : '  询价清单以及要求' }}


    </div>
    <el-form ref="addForm"
             :model="forwarderInquiry"
             label-width="auto"
             style="
        max-width:1000px;
        margin: auto;
        background-color: #fff;
        padding: 20px;
        border: 1px solid #ccc"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户姓名:">
            <!--            输入监听事件，自动填充客户姓名-->
            <el-input
              v-model="forwarderInquiry.customer_name"
              placeholder="默认填充，直接创建的可以手动填写"
              style="margin-right: 20px;"
              @input="handleCustomerNameInput"
            />
          </el-form-item>

        </el-col>
        <el-col :span="12">
          <el-form-item label="询价编码:">
            <el-input v-model="forwarderInquiry.quote_coding" placeholder="默认填充，直接创建的可以手动填写"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
<!--                      format="yyyy-MM-dd HH:mm:ss"-->
        <el-col :span="12">
          <el-form-item label="询价日期:">
            <el-date-picker
              v-model="forwarderInquiry.quote_data"
              type="datetime"


              placeholder="请选择日期"
              style="width: 388px;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="货物种类:">
            <el-input v-model="forwarderInquiry.type_goods" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="运输方式:">
            <el-select v-model="forwarderInquiry.transport_way" placeholder="海运/铁路/公路/空运/多联式/散货"
                       style="margin-right: 20px;">
              <el-option
                v-for="item in method"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="航线选择">
            <el-select v-model="forwarderInquiry.route" placeholder="请选择">
              <el-option v-for="item in airline" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="起运港:">
            <el-input v-model="forwarderInquiry.port_of_departure" placeholder="请输入" style="margin-right: 20px;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目的港:">
            <el-input v-model="forwarderInquiry.port_of_destination" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="报价条款:">
            <el-select v-model="forwarderInquiry.quotation_terms" placeholder="请选择 " style="width: 388px;">
              <el-option v-for="item in offerTerms" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="货物描述:">
            <el-input v-model="forwarderInquiry.description_goods" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="HS编码:">
            <el-input v-model="forwarderInquiry.hs_code" placeholder="请输入" style="margin-right: 20px;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="柜型选择:">
            <el-select v-model="forwarderInquiry.cabinet_type" placeholder="请选择 ">
              <el-option v-for="item in cabinetType" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div
      class="tip"
    >
      产品信息
    </div>

    <el-table :data="tableData" style="
        max-width:1000px;
        margin: auto;
        background-color: #fff;
        padding: 20px;
        border: 1px solid #ccc">
      <el-table-column prop="product_number" label="产品编号" width="120"/>
      <el-table-column prop="product_name" label="产品名称" width="120"/>
      <el-table-column label="总件数" width="180">
        <template #default="scope">
          <el-input-number v-model="scope.row.pieces"/>
        </template>
      </el-table-column>
      <el-table-column label="总毛重 (kg)" width="180">
        <template #default="scope">
          <el-input-number v-model="scope.row.gross_weight"/>
        </template>
      </el-table-column>
      <el-table-column label="总体积 (CBM)" width="180">
        <template #default="scope">
          <el-input-number v-model="scope.row.volume"/>
        </template>
      </el-table-column>
      <el-table-column label="总托数" width="180">
        <template #default="scope">
          <el-input-number v-model="scope.row.support_number"/>
        </template>
      </el-table-column>

    </el-table>

    <!--分页-->
    <div
      class="tip"

    >
      <el-pagination
        background
        :page-size="pageSize"
        layout="total,sizes,prev, pager, next,jumper"
        :total="total"
        @size-change="chgsize"
        @current-change="chgpg"
      />
    </div>

    <div style="text-align: center; margin: 20px">
      <el-button type="primary" @click="save">{{ isEditMode ? '更新' : '保存' }}</el-button>
      <el-button type="info" @click="close">取消</el-button>
    </div>

  </div>

</template>

<!--vue 组件选项定义-->
<script setup>
import {ref, onBeforeMount, onMounted} from "vue";
import {useRouter, useRoute} from "vue-router";
import {ElMessage} from "element-plus";
//引入api
import {
  queryForwarderProduct,
  saveForwarderInquiry,
  getForwarderInquiryById,
  updateForwarderInquiry,
  queryCustomerInquiryDetailsByName
} from "@/api/forwarderInquiry.js";
import {queryForwarderProductByInquiryId,updateHasForwarderInquiry} from "@/api/customerinquiry.js";
//路由实例
const router = useRouter();
const route = useRoute();


const isEditMode = ref(false); // 判断是添加还是编辑模式
const inquiryId = ref(null); // 用于存储编辑时的询价ID


const method = [
  {
    label: "海运",
    value: 1
  },
  {
    label: "铁路",
    value: 2
  },
  {
    label: "公路",
    value: 3
  }, {
    label: "空运",
    value: 4
  },
  {
    label: "多联式",
    value: 5
  },
  {
    label: "散货",
    value: 6
  }
];
const airline = [
  {
    label: "中国-北美",
    value: 1
  },
  {
    label: "中国-美加",
    value: 2
  },
  {
    label: "中国-欧洲",
    value: 3
  },
  {
    label: "中国-澳大利亚/新西兰",
    value: 4
  },
  {
    label: "中国-中南美",
    value: 5
  },
  {
    label: "中国-红海/地中海",
    value: 6
  },
  {
    label: "中国-日本/韩国/俄罗斯",
    value: 7
  },
  {
    label: "中国-东南亚",
    value: 8
  },
  {
    label: "中国-中东/波斯湾",
    value: 9
  },
  {
    label: "中国-中东/印巴",
    value: 10
  },
  {
    label: "中国-黑海/亚德里海湾",
    value: 11
  },
  {
    label: "中国-南美东/南美西",
    value: 12
  },
  {
    label: "中国-欧洲内陆",
    value: 13
  },
  {
    label: "中国-东非",
    value: 14
  },
  {
    label: "中国-西非",
    value: 15
  },
  {
    label: "中国-南非",
    value: 16
  },
  {
    label: "中国-北非",
    value: 17
  },
  {
    label: "中国-加勒比海",
    value: 18
  },
  {
    label: "中国-大马士革",
    value: 19
  },
  {
    label: "中国-科隆",
    value: 20
  },
  {
    label: "中国-菲律宾",
    value: 21
  },
  {
    label: "中国-香港/澳门",
    value: 22
  }
];
//报价条款
const offerTerms = [
  {
    label: "CFR",
    value: 1
  },
  {
    label: "CIF",
    value: 2
  },
  {
    label: "DDU",
    value: 3
  },
  {
    label: "DAP",
    value: 4
  },
  {
    label: "DDP",
    value: 5
  },
  {
    label: "其他",
    value: 6
  }
];
//柜型选择
const cabinetType = [
  {
    label: "拼箱",
    value: 1
  },
  {
    label: "20GP",
    value: 2
  },
  {
    label: "40GP",
    value: 3
  },
  {
    label: "20HQ",
    value: 4
  },
  {
    label: "40HQ",
    value: 5
  },
  {
    label: "20FR",
    value: 6
  }
  ,
  {
    label: "40FR",
    value: 7
  }
  ,
  {
    label: "200T",
    value: 8
  },
  {
    label: "400P",
    value: 9
  }
  ,
  {
    label: "散货",
    value: 10
  }
]
//分页信息
const page = ref(1); //当前页 默认第1页
const pageSize = ref(10); //每页记录数
const total = ref(0); //总记录数
//表格数据
const tableData = ref([]);

//每页记录数变化
function chgsize(size) {
  //更改每页记录数
  pageSize.value = size;
  //从每页开始查询
  page.value = 1;
  //查询数据
  //查询数据
  if (route.query.id) {
    loadInquiryData(inquiryId.value);
  } else if (route.query.InquiryId) {
    loadProductDataByInquiryId(inquiryId.value);
  } else {
    // initData();
  }
}

//页面发生变化
function chgpg(pg) {
  //更改当前页
  page.value = pg;
  //查询数据
  if (route.query.id) {
    loadInquiryData(inquiryId.value);
  } else if (route.query.InquiryId) {
    loadProductDataByInquiryId(inquiryId.value);
  } else {
    // initData();
  }
}


//表单引用  声明同名引用
const addForm = ref();

//表单对象
const forwarderInquiry = ref({
  customer_id: "",
  customer_name: "",
  quote_coding: "",
  quote_data: "",
  type_goods: "",
  transport_way: "",
  route: "",
  port_of_departure: "上海",
  port_of_destination: "",
  quotation_terms: "",
  description_goods: "",
  hs_code: "84749000",
  cabinet_type: "",
 /* product_number: "",
  product_name: "",
  pieces: "",
  gross_weight: "",
  volume: "",
  support_number: "",*/
  products: [], // 产品信息列表


});


//取消
function close() {
  router.push("/forwarder/inquiry/");
}

/**
 * 区分是保存还是编辑
 * @returns {Promise<void>}
 */
async function save() {

  // 将 value 替换为 label
  forwarderInquiry.value.transport_way = method.find(item => item.value === forwarderInquiry.value.transport_way)?.label;
  forwarderInquiry.value.route = airline.find(item => item.value === forwarderInquiry.value.route)?.label;
  forwarderInquiry.value.quotation_terms = offerTerms.find(item => item.value === forwarderInquiry.value.quotation_terms)?.label;
  forwarderInquiry.value.cabinet_type = cabinetType.find(item => item.value === forwarderInquiry.value.cabinet_type)?.label;

  forwarderInquiry.value.customer_id = route.query.customer_id; // 客户ID
  if (isEditMode.value) {
    // 将表格数据赋值给 forwarderInquiry.products
    forwarderInquiry.value.products = tableData.value;

    //如果是编辑模式，调用更新Api
    let res = await updateForwarderInquiry(forwarderInquiry.value);
    if (res.code === 200) {
      ElMessage({
        message: "更新成功",
        type: "success"
      });
      close();
    }
  } else {
    // 将表格数据赋值给 forwarderInquiry.products
    forwarderInquiry.value.products = tableData.value;
    //如果是添加模式，调用保存Api
    let res = await saveForwarderInquiry(forwarderInquiry.value);
    console.log("保存的货代询价单信息",forwarderInquiry.value)
    if (res.code === 200) {
      ElMessage({
        message: "保存成功",
        type: "success"
      });
      let edit = await updateHasForwarderInquiry(code);
      if (edit.code === 200) {
        close();
      }
    }
  }
}
const code = route.query.code;
/**
 * 初始化数据,加载产品表里的所有数据（可能不需要）
 * @returns {Promise<void>}
 */
/*async function initData() {
  //请求
  let data = {
    page: page.value,
    pageSize: pageSize.value,
  };
  let res = await queryForwarderProduct(data);
  if (res.code === 200) {
    tableData.value = res.data.data;
    //接收分页信息
    page.value = res.data.page;
    pageSize.value = res.data.pageSize;
    total.value = res.data.total;
  }
}*/


/**
 * 仅传id进入编辑模式
 * @param id
 * @returns 加载编辑时的询价数据
 */
async function loadInquiryData(id) {
  //请求
  console.log("loadInquiryData", id)
  let data = {
    page: page.value,
    pageSize: pageSize.value,
  };
  let res = await getForwarderInquiryById(id,data.page,data.pageSize);
  console.log("修改拿到的数据", res)
  if (res.code === 200) {
    forwarderInquiry.value = res.data.data[0];

    // 将 label 映射回 value
    forwarderInquiry.value.transport_way = method.find(item => item.label === forwarderInquiry.value.transport_way)?.value;
    forwarderInquiry.value.route = airline.find(item => item.label === forwarderInquiry.value.route)?.value;
    forwarderInquiry.value.quotation_terms = offerTerms.find(item => item.label === forwarderInquiry.value.quotation_terms)?.value;
    forwarderInquiry.value.cabinet_type = cabinetType.find(item => item.label === forwarderInquiry.value.cabinet_type)?.value;
    // 确保 tableData.value 是一个数组
    tableData.value = forwarderInquiry.value.products || [];
    //接收分页信息
    page.value = res.data.page;
    pageSize.value = res.data.pageSize;
    total.value = res.data.total;
  }
}

/**
 * 根据客户询价单id加载产品信息
 * @param InquiryId 客户询价单ID
 * @returns
 */
async function loadProductDataByInquiryId(inquiryId) {
  //请求
  let data = {
    page: page.value,
    pageSize: pageSize.value,
  };
  let res = await queryForwarderProductByInquiryId(inquiryId, data.page, data.pageSize);
  if (res.code === 200) {
    console.log("res表格数据", res)
    tableData.value = res.data.data;
    //接收分页信息
    page.value = res.data.page;
    pageSize.value = res.data.pageSize;
    total.value = res.data.total;
  }
}

/**
 * 监听客户姓名输入框，请求客户询价单产品列表
 * @returns
 */
async function handleCustomerNameInput() {

  if (forwarderInquiry.value.customer_name) {
    let data = {
      page: page.value,
      pageSize: pageSize.value,
      customer_name: forwarderInquiry.value.customer_name

    };
    let res = await queryCustomerInquiryDetailsByName(data.customer_name, data.page, data.pageSize);
    if (res.code === 200) {
      console.log("res表格数据", res)
      // 将查询结果绑定到表格中
      tableData.value = res.data.data.map(item => ({
        product_number: item.product_number, // 产品编号
        product_name: item.product_name, // 产品名称
        pieces: item.pieces || 0, // 总件数
        gross_weight: item.gross_weight || 0, // 总毛重
        volume: item.volume || 0, // 总体积
        support_number: item.support_number || 0 // 总托数
      }));
      //接收分页信息
      page.value = res.data.page;
      pageSize.value = res.data.pageSize;
      total.value = res.data.total;
    }

  }
}

// 在 script setup 部分添加格式化日期的函数
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
}



//生命周期
onBeforeMount(() => {


  if (route.query.id) {
    isEditMode.value = true;
    inquiryId.value = route.query.id;
    loadInquiryData(inquiryId.value);
  } else if (route.query.InquiryId) {
    // 如果是新增模式，并且携带了 InquiryId
    isEditMode.value = false;
    // 加载产品信息
    inquiryId.value = route.query.InquiryId;
    // 将路由传递的 customerName 赋值给客户姓名
    const currentDate = new Date();
    forwarderInquiry.value.quote_data = formatDate(currentDate); // 自动填充询价日期
    forwarderInquiry.value.customer_name = route.query.contactName;
    loadProductDataByInquiryId(inquiryId.value);
  } else {
    const currentDate = new Date();
    forwarderInquiry.value.quote_data = formatDate(currentDate); // 自动填充询价日期
    console.log(forwarderInquiry.value.quote_data);
    // initData();
  }
});
</script>

<!--vue样式 scoped当前样式只适用于当前组件-->
<style scoped>
.ipt {
  width: 300px;
}

.tip {
  width: 1000px;
  margin: auto;
  height: 60px;
  line-height: 60px;
  border: #ccc solid 1px;
  padding-left: 40px;
}
</style>
